package cn.itcast.bos.web.action;

import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.mail.MessagingException;
import javax.servlet.ServletContext;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;

import cn.itcast.bos.constant.Constants;
import cn.itcast.bos.utils.MailUtils;
import cn.itcast.bos.utils.SmsDemoUtils;
import cn.itcast.bos.web.action.common.BaseAction;
import cn.itcast.crm.domain.Customer;




@ParentPackage("json-default")
@Namespace("/")
@Controller()
@Scope(value="prototype")
public class CustomerAction extends BaseAction<Customer> {
	@Autowired
	private RedisTemplate<String, String> redisTemplate;
	@Autowired
	@Qualifier("jmsQueueTemplate")
	private JmsTemplate jmsTemplate;
	@Action(value = "customer_sendSms",results={@Result(name="success",type="json")})
	public String sendSms() {
		//System.out.println(model.getTelephone());
		final String telephone=model.getTelephone();
		
		
		//手机验证码
		final String number = SmsDemoUtils.getNumber();
		HashMap<String,Object> map = new HashMap<String,Object >();
		//session校验
		ServletActionContext.getRequest().getSession().setAttribute(telephone, number);
		ServletActionContext.getRequest().getSession().setMaxInactiveInterval(60);
		try {
			//SendSmsResponse sendSms = SmsDemoUtils.sendSms(telephone, number);
			//jms生产消息
			jmsTemplate.send("bos_sms",new MessageCreator() {
				
				@Override
				public Message createMessage(Session session) throws JMSException {
					MapMessage mapMessage = session.createMapMessage();
					mapMessage.setString("telephone", telephone);
					mapMessage.setString("code", number);
					return mapMessage;				
					
				}
			});
			String code="OK";
			if(code.equals("OK")){
				System.out.println("短信发送成功！手机号是："+telephone+"，验证码是："+number);
				map.put("success", "发送成功");
				map.put("telephone", telephone);
				map.put("checkcode", number);
			}
			
		} catch (Exception e) {
			map.put("error", "发送失败");
			e.printStackTrace();
		}
		ServletActionContext.getContext().getValueStack().push(map);
		return SUCCESS;
		}
	private String checkcode;
	
	public void setCheckcode(String checkcode) {
		this.checkcode = checkcode;
	}
    @Action(value = "customer_regist", results = {
			@Result(name = "success", type = "redirect", location = "signup-success.html"),
			@Result(name = "input", type = "redirect", location = "signup.html") })
	public String regist() throws Exception {
    	String checkcodeSession = (String) ServletActionContext.getRequest()
				.getSession().getAttribute(model.getTelephone());
		if (checkcodeSession == null || !checkcodeSession.equals(checkcode)) {
			System.out.println("短信验证码错误...");
			// 短信验证码错误
			return INPUT;
		}
		WebClient.create(Constants.CRM_MANAGEMENT_URL)
		.path("/services/customerService/customer")
		.type(MediaType.APPLICATION_JSON) // 表示传递的参数
		.post(model);
		String activecode = RandomStringUtils.randomNumeric(32);

		// 将激活码保存到redis，设置24小时失效
		redisTemplate.opsForValue().set(model.getTelephone(), activecode, 24,TimeUnit.HOURS);

		// 调用MailUtils发送激活邮件
		// 传递电话和激活码的目的是：在激活的代码中和redis中的数据进行比对。
		String content = "尊敬的客户您好，请于24小时内，进行邮箱账户的绑定，点击下面地址完成绑定:<br/><a href='"
				+ MailUtils.activeUrl + "?telephone=" + model.getTelephone()
				+ "&activecode=" + activecode + "'>速运快递邮箱绑定地址</a>";
		/**
		 * 参数一：标题
		 * 参数二：内容
		 * 参数三：发送的邮件地址（页面上获取）
		 */
		
		MailUtils.sendMail("速运快递激活邮件", content, model.getEmail(),"");
		System.out.println("客户注册成功！");
		return SUCCESS;
    }
    private String activecode;
    
    public void setActivecode(String activecode) {
		this.activecode = activecode;
	}
	@Action("customer_activeMail")
	public String activeMail() throws Exception {
    	ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
    	String activeCodeRedis = redisTemplate.opsForValue().get(model.getTelephone());
    	if (activecode==null||activecode.equalsIgnoreCase(activeCodeRedis) ){
    		// 激活码无效
    	ServletActionContext.getResponse().getWriter().println("激活码无效，请登录系统，重新绑定邮箱！");
		}else{
			Customer customer = WebClient.create(Constants.CRM_MANAGEMENT_URL+"/services/customerService/customer/telephone/"+model.getTelephone()).
			accept(MediaType.APPLICATION_JSON).
			type(MediaType.APPLICATION_JSON).
			get(Customer.class);
			if (customer==null||customer.getType()!=1) {
				//重新绑定
				WebClient.create(Constants.CRM_MANAGEMENT_URL+"/services/customerService/customer/updatetype/"+model.getTelephone()).accept(MediaType.APPLICATION_JSON).
				type(MediaType.APPLICATION_JSON).put(null);
				ServletActionContext.getResponse().getWriter().println("邮箱绑定成功！");
				
			}else{
				ServletActionContext.getResponse().getWriter().println("邮箱已经绑定过，无需重复绑定！");
				
			}
			redisTemplate.delete(model.getTelephone());
		}
    	return NONE;
    }
	
	} 
